import deviceFooter from '@/assets/screen/subsystem/device-footer.png';
import deviceTitle from '@/assets/screen/subsystem/device-title.png';
import faultBorder from '@/assets/screen/subsystem/fault-border.png';
import fault from '@/assets/screen/subsystem/fault.png';
import importDataItemError from '@/assets/screen/subsystem/import-data-item-error.png';
import importDataItem from '@/assets/screen/subsystem/import-data-item.png';
import lowBorder from '@/assets/screen/subsystem/low-border.png';
import low from '@/assets/screen/subsystem/low.png';
// import monthStatusBg from '@/assets/screen/subsystem/month-status-bg.png';
import noneBorder from '@/assets/screen/subsystem/none-border.png';
import none from '@/assets/screen/subsystem/none.png';
import paramItemActive from '@/assets/screen/subsystem/param-item-active.png';
import paramItemErrorActive from '@/assets/screen/subsystem/param-item-error-active.png';
import paramItemError from '@/assets/screen/subsystem/param-item-error.png';
import paramItem from '@/assets/screen/subsystem/param-item.png';
import paramTitle from '@/assets/screen/subsystem/param-title.png';
import perfectBorder from '@/assets/screen/subsystem/perfect-border.png';
import perfect from '@/assets/screen/subsystem/perfect.png';
import statusHeader from '@/assets/screen/subsystem/status-header.png';
import BaseButton from '@/components/base/BaseButton';
import { getRealFileUrl } from '@/config/config';
import { useQuery } from '@/router';
import useScreenStore from '@/store/screen';
import { useRequest } from '@/utils/request';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import { Calendar, DatePicker, Radio, Spin } from 'antd';
import classNames from 'classnames';
import moment from 'moment';
import { useRef, useState } from 'react';
import styled from 'styled-components';
import { DataModel, getSubSystemData, getSubSystemMonthStatusData, pollingInterval } from '../api';
import Box from '../components/Box';
import HisData from '../components/HisData';
import ScreenLayout from '../Screen/Layout';
import { fixHeight, fixWidth } from '../util';
import AdaptaionParameterList from './components/AdaptaionParameterList';

const ParamList = styled.div`
  display: flex;
  flex-wrap: wrap;
  .params-list-item {
    width: 33%;
    margin: 0.15%;
    display: flex;
    justify-content: space-between;
    background-image: url('${paramItem}');
    background-size: 100% 100%;
    height: ${fixHeight(57)};
    font-size: ${fixHeight(12)};
    align-items: center;

    &.params-list-item-active {
      background-image: url('${paramItemActive}');
    }
    &.item-error {
      background-image: url('${paramItemError}');
      &.params-list-item-active {
        background-image: url('${paramItemErrorActive}');
      }
    }
    &--label {
      width: 50%;
      text-align: center;
    }
    &--content {
      width: 50%;
      text-align: center;
    }
  }
`;
const Container = styled.div`
  height: 100%;
  width: 100%;
  display: flex;
  padding: 0 ${fixWidth(6)};
  flex-wrap: wrap;
  .select-type {
    .ant-radio-wrapper {
      color: #fff;
      font-size: ${fixHeight(14)};
      height: ${fixHeight(22)};
      .ant-radio {
        display: none;
      }
    }
    .ant-radio-wrapper-checked {
      border-radius: ${fixHeight(22)};
      background: #76c8ce;
    }
  }
  &&& .ant-picker {
    background: linear-gradient(90deg, #066a8e 0%, #005883 100%);
    border-image: linear-gradient(0deg, #066a8e, #00acff) 10 10;

    &-suffix,
    input,
    .anticon {
      color: #fff;
    }
    &-clear {
      background: linear-gradient(90deg, #066a8e 0%, #005883 100%);
      color: #fff;
    }
  }
  & > div {
    margin: ${fixHeight(8)};
    height: ${fixHeight(480)};
    width: calc(50% - ${fixHeight(16)});
    overflow: hidden;
  }
  .important {
    .important-wrap {
      display: flex;
    }
    &-status {
      flex-basis: 30%;
      margin-left: 10%;
      flex-shrink: 0;
      text-align: center;
      .device-picture {
        height: 80%;
        position: relative;
        .deivce {
          position: absolute;
          left: 50%;
          top: 40%;
          transform: translate(-50%, -40%);
        }
        .device-footer {
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          z-index: 0;
        }
      }
      .device-title {
        background-image: url('${deviceTitle}');
        background-size: 100% 100%;
        width: ${fixWidth(189)};
        height: ${fixHeight(46)};
        line-height: ${fixHeight(36)};
        font-size: ${fixHeight(24)};
        margin: ${fixHeight(10)} auto;
      }
    }
  }
  .list {
    flex: 1;
    overflow: auto;
    &--item {
      width: 80%;
      margin: ${fixHeight(10)} auto;
      display: flex;
      background-image: url('${importDataItem}');
      background-size: 100% 100%;
      height: ${fixHeight(33)};
      flex-shrink: 0;
      line-height: ${fixHeight(33)};
      font-size: ${fixHeight(14)};
      text-align: center;
      &.error {
        background-image: url('${importDataItemError}');
      }
      &__title {
        width: 45%;
      }
      &__content {
        flex: 1;
      }
    }
  }
  .params {
    &-title {
      text-align: center;
      background-image: url('${paramTitle}');
      background-size: 100% 100%;
      height: ${fixHeight(55)};
      padding-top: ${fixHeight(5)};
      line-height: ${fixHeight(50)};
    }
  }

  .month-status {
    .wrap {
      padding: ${fixHeight(20)};
      flex-direction: column;
      position: relative;
    }
    .ant-spin-nested-loading,
    .ant-spin-container {
      height: 100%;
    }
    .action {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #fff;
      font-size: ${fixHeight(16)};
      background-image: url('${statusHeader}');
      background-size: 100% 100%;
      height: ${fixHeight(32)};
      .ant-btn {
        width: ${fixHeight(32)};
        height: ${fixHeight(32)};
        color: #fff;
        font-size: ${fixHeight(16)};
      }
    }
    .ant-picker-calendar {
      background: transparent;
      height: 100%;
      display: flex;
      flex-direction: column;
    }
    .ant-picker-panel {
      background: transparent;
      border: none;
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: column;
    }
    .ant-picker-body {
      padding: ${fixHeight(10)} ${fixWidth(24)} ${fixHeight(42)} ${fixWidth(30)}!important;
    }
    .ant-picker-content {
      height: auto;
      th {
        color: #fff;
        line-height: ${fixHeight(32)};
        font-size: ${fixHeight(16)};
      }
    }
    .ant-picker-cell {
      padding: ${fixHeight(4)} ${fixWidth(4)};
      border: none;
      opacity: 0;
      pointer-events: none;
      color: #666;

      &.ant-picker-cell-in-view {
        opacity: 1;
        pointer-events: auto;
        color: #fff;
      }
      & > div {
        height: 100%;
      }
    }
    .status-list {
      display: flex;
      justify-content: space-around;
      text-align: center;
      position: absolute;
      right: ${fixWidth(20)};
      bottom: ${fixHeight(20)};
      height: ${fixHeight(42)};
      width: ${fixWidth(520)};
      .item {
        width: ${fixWidth(90)};
        background-repeat: no-repeat;
        background-size: 100% 100%;
        line-height: ${fixHeight(42)};
        &.none {
          background-image: url('${noneBorder}');
        }
        &.perfect {
          background-image: url('${perfectBorder}');
        }
        &.low {
          background-image: url('${lowBorder}');
        }
        &.fault {
          background-image: url('${faultBorder}');
        }
      }
    }
  }
  .history {
  }
`;
const CellStatus = styled.div`
  height: 100%;
  line-height: ${fixHeight(36)};
  font-size: ${fixHeight(20)};
  background-repeat: no-repeat;
  background-size: 100% 100%;
  /* min-width: ${fixWidth(112)};
  max-width: 100%; */
  width: 100%;
  &.none {
    background-image: url('${none}');
  }
  &&&.perfect {
    background-image: url('${perfect}');
  }
  &&&.low {
    background-image: url('${low}');
  }
  &&&.fault {
    background-image: url('${fault}');
  }
`;
const AdaptarContainer = styled.div`
  display: flex;
  flex-direction: column;
  padding: ${fixHeight(16)};
  height: 100%;
  overflow: hidden;
  &&& .ant-picker {
    background: linear-gradient(90deg, #066a8e 0%, #005883 100%);
    border-image: linear-gradient(0deg, #066a8e, #00acff) 10 10;

    &-suffix,
    input,
    .anticon {
      color: #fff;
    }
    &-clear {
      background: linear-gradient(90deg, #066a8e 0%, #005883 100%);
      color: #fff;
    }
  }
  .data-list {
    display: flex;
    margin-bottom: ${fixHeight(16)};
    .data-list-item {
      width: 50%;
      height: ${fixHeight(360)};
      .box-wrap {
        overflow: auto;
      }
      & + .data-list-item {
        margin-left: ${fixHeight(16)};
      }
    }
  }
  .data-table {
    height: ${fixHeight(590)};
    overflow: hidden;
  }
`;
const statusClass = ['perfect', 'low', 'fault'];
/**
 *
 * @param str1
 * @param str2
 * @returns
 */
function diffName(str1 = '', str2 = '') {
  let shorter, longer;
  if (str1 > str2) {
    shorter = str2;
    longer = str1;
  } else {
    shorter = str1;
    longer = str2;
  }
  let maxs = '';
  for (let a = shorter.length; a > 0; a -= 1) {
    if (maxs.length > 0) break;
    for (let b = 0; a + b < shorter.length; b += 1) {
      const str = shorter.substring(b, a + b);

      if (longer.indexOf(str) >= 0) {
        maxs = str;
        break;
      }
    }
  }

  return maxs.length > 0
    ? `${maxs}(${str1.replace(maxs, '')}/${str2.replace(maxs, '')})`
    : [str1, str2].filter((i) => i !== '').join('/');
}

const needMerge = (data: DataModel[]) => {
  const maps: Record<string, DataModel & { origins: DataModel[] }> = {};
  data.forEach((i) => {
    if (i.displayLocationName in maps) {
      if (i.CName.includes('实测')) {
        maps[i.displayLocationName].value = `${i.value}/${maps[i.displayLocationName].value}`;
        maps[i.displayLocationName].CName = `${i.CName},${maps[i.displayLocationName].CName}`;
        maps[i.displayLocationName].EName = `${i.EName},${maps[i.displayLocationName].EName}`;
      } else {
        maps[i.displayLocationName].value += `/${i.value}`;
        maps[i.displayLocationName].CName += `,${i.CName}`;
        maps[i.displayLocationName].EName += `,${i.EName}`;
      }
      maps[i.displayLocationName].origins.push(i);
      if (maps[i.displayLocationName].origins.findIndex((i) => i.status === 1) !== -1) {
        maps[i.displayLocationName].status = 1;
      }
    } else {
      maps[i.displayLocationName] = {
        displayLocationName: i.displayLocationName,
        order: i.order,
        value: i.value,
        EName: i.EName,
        CName: i.CName,
        unit: i.unit,
        status: i.status,
        origins: [i]
      };
    }
  });
  const values = Object.values(maps);
  return values.sort((a, b) => a.order - b.order);
};
const SubSystem = () => {
  const [activeItem, setActiveItem] = useState<DataModel & { origins?: DataModel[] }>();
  const query = useQuery();
  const radarId = query.get('radarId')!;
  const subsystemId = query.get('subsystemId')!;
  const subSystemName = query.get('subSystemName')!;

  const isSystemParam = subSystemName === '系统标定';
  const isAdaptar = subSystemName === '适配参数';
  const { time, setTime } = useScreenStore();
  const month = useRef(moment().format('yyyy-MM'));
  const [type, setType] = useState<'0' | '1' | '2'>('0');
  const realData = useRequest(getSubSystemData, {
    defaultParams: [{ radarId, subsystemId }],
    pollingInterval,
    onSuccess(data) {
      setTime(data.time);
      if (!activeItem) {
        if (data.showData.length > 0) {
          if (isSystemParam) {
            const mergeList = needMerge(data.showData[0].list);
            setActiveItem(mergeList[0]);
          } else {
            setActiveItem(data.showData[0].list[0]);
          }
        }
      }
    }
  });
  const status = useRequest(getSubSystemMonthStatusData, {
    defaultParams: [
      {
        time: month.current,
        radarId,
        subsystemId
      }
    ]
  });
  const [date, setDate] = useState<[string, string] | undefined>(() =>
    isAdaptar
      ? [moment().month(1).startOf('month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      : undefined
  );
  return (
    <ScreenLayout>
      {isAdaptar ? (
        <AdaptarContainer>
          <div className='data-list'>
            <Box title='静态参数' className='data-list-item'>
              <ParamList>
                {realData.data?.importData.map((i) => (
                  <div
                    className={classNames('params-list-item', {
                      'params-list-item-active': activeItem?.EName === i.EName
                      // 'item-error': i.status === 1
                    })}
                    key={i.EName}
                    onClick={() => {
                      setActiveItem(i);
                    }}
                  >
                    <span className='params-list-item--label'>{i.CName}</span>
                    <span className='params-list-item--content'>
                      {i.value}
                      {i.unit}
                    </span>
                  </div>
                ))}
              </ParamList>
            </Box>
            <Box
              title='适配参数'
              className='data-list-item'
              headerAction={[<div>更新时间：{time}</div>]}
            >
              {realData.data?.showData
                .sort((a, b) => a.order - b.order)
                .map((i) => (
                  <ParamList key={i.displayName}>
                    {i.list
                      .sort((a, b) => a.order - b.order)
                      .map((l) => (
                        <div
                          data-item={l.status === 1}
                          className={classNames('params-list-item', {
                            'params-list-item-active': activeItem?.EName === l.EName
                            // 'item-error': l.status === 1
                          })}
                          key={l.EName}
                          onClick={() => {
                            setActiveItem(l);
                          }}
                        >
                          <span className='params-list-item--label'>{l.CName}</span>
                          <span className='params-list-item--content'>
                            {l.value}
                            {l.unit}
                          </span>
                        </div>
                      ))}
                  </ParamList>
                ))}
            </Box>
          </div>
          <div className='data-table'>
            {radarId && (
              <Box
                title={`${activeItem?.CName ?? ''} 更新记录`}
                headerAction={[
                  <DatePicker.RangePicker
                    defaultValue={date ? [moment(date[0]), moment(date[1])] : undefined}
                    onChange={(d, ds) => {
                      if (d) {
                        setDate(ds);
                      } else {
                        setDate(undefined);
                      }
                    }}
                  />
                ]}
              >
                <AdaptaionParameterList times={date} radarId={radarId} item={activeItem} />
              </Box>
            )}
          </div>
        </AdaptarContainer>
      ) : (
        <Container>
          <Box className='important' title={`${subSystemName}重要参数`} bodyClass='important-wrap'>
            <div className='important-status'>
              <div className='device-picture'>
                <img className='device-footer' src={deviceFooter} />
                {realData.data?.pictureStatus && (
                  <img className='deivce' src={getRealFileUrl(realData.data?.pictureStatus)} />
                )}
              </div>
              <div className='device-title'>{realData.data?.status}</div>
            </div>
            <div className='list'>
              {realData.data?.importData.map((i) => {
                return (
                  <div
                    className={classNames('list--item', {
                      error: isSystemParam ? false : i.status === 1
                    })}
                    key={i.EName}
                  >
                    <div className='list--item__title'>
                      {/* {i.picture ? <img src={getRealFileUrl(i.picture)} /> : i.CName} */}
                      {i.CName}
                    </div>
                    <div className='list--item__content'>
                      {i.value}
                      {i.unit}
                    </div>
                  </div>
                );
              })}
            </div>
          </Box>
          <Box className='params' title='性能参数' headerAction={[<div>更新时间：{time}</div>]}>
            <div style={{ height: '100%', overflow: 'auto' }}>
              {realData.data?.showData
                .sort((a, b) => a.order - b.order)
                .map((i) => (
                  <div key={i.displayName}>
                    <div className='params-title'>{i.displayName}</div>
                    <ParamList>
                      {isSystemParam
                        ? needMerge(i.list).map((l) => {
                            return (
                              <div
                                className={classNames('params-list-item', {
                                  'params-list-item-active': activeItem?.EName === l.EName,
                                  'item-error': l.status === 1
                                })}
                                key={l.displayLocationName}
                                onClick={() => {
                                  setActiveItem(l);
                                }}
                              >
                                <span className='params-list-item--label'>
                                  {diffName(...l.CName.split(','))}
                                </span>
                                <span className='params-list-item--content'>
                                  {l.value}
                                  {l.unit}
                                </span>
                              </div>
                            );
                          })
                        : i.list
                            .sort((a, b) => a.order - b.order)
                            .map((l) => (
                              <div
                                className={classNames('params-list-item', {
                                  'params-list-item-active': activeItem?.EName === l.EName,
                                  'item-error': l.status === 1
                                })}
                                key={l.EName}
                                onClick={() => {
                                  setActiveItem(l);
                                }}
                              >
                                <span className='params-list-item--label'>{l.CName}</span>
                                <span className='params-list-item--content'>
                                  {l.value}
                                  {l.unit}
                                </span>
                              </div>
                            ))}
                    </ParamList>
                  </div>
                ))}
            </div>
          </Box>
          <Box className='month-status' bodyClass='wrap' title={`${subSystemName}月状态`}>
            <Spin spinning={status.loading}>
              <Calendar
                fullscreen={false}
                dateFullCellRender={(date) => {
                  const ymd = date.format('yyyy-MM-DD');
                  const hasData = date <= moment();
                  const isCurrentMonth = date.format('yyyy-MM') === month.current;
                  let className = '';
                  if (hasData && isCurrentMonth && status.data) {
                    const data = status.data[ymd];
                    className = statusClass[data];
                  }
                  return (
                    <CellStatus className={classNames('none', className)}>
                      {date.format('DD')}
                    </CellStatus>
                  );
                }}
                onPanelChange={(date) => {
                  const m = date.format('yyyy-MM');
                  month.current = m;
                  status.run({ time: m, radarId, subsystemId });
                }}
                headerRender={({ value, onChange }) => {
                  const current = value.clone();
                  return (
                    <div className='action'>
                      <BaseButton
                        type='text'
                        icon={<LeftOutlined />}
                        onClick={() => {
                          onChange(current.add(-1, 'month'));
                        }}
                      />
                      {current.format('YYYY年MM月')}
                      <BaseButton
                        type='text'
                        icon={<RightOutlined />}
                        onClick={() => {
                          onChange(current.add(1, 'month'));
                        }}
                      />
                    </div>
                  );
                }}
              />
            </Spin>
            <div className='status-list'>
              <div className='item perfect'>正常</div>
              <div className='item low'>弱化</div>
              <div className='item fault'>故障</div>
              <div className='item none'>未记录</div>
            </div>
          </Box>
          <Box
            className='history'
            title='历史数据'
            headerAction={[
              <Radio.Group
                defaultValue={type}
                className='select-type'
                options={[
                  { label: '日', value: '0' },
                  { label: '月', value: '1' },
                  { label: '季度', value: '2' }
                ]}
                onChange={(e) => {
                  setType(e.target.value);
                }}
              />,
              <DatePicker.RangePicker
                onChange={(d, ds) => {
                  if (d) {
                    setDate(ds);
                  } else {
                    setDate(undefined);
                  }
                }}
              />
            ]}
          >
            <HisData
              // eslint-disable-next-line no-nested-ternary
              data={isSystemParam ? activeItem?.origins : activeItem ? [activeItem] : []}
              type={type}
              times={date}
              radarId={query.get('radarId')}
            />
          </Box>
        </Container>
      )}
    </ScreenLayout>
  );
};

export default SubSystem;
